
package com.platform.modules.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.annotation.LoginUser;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.*;
import com.platform.modules.app.entity.BuyGoodsVo;
import com.platform.modules.app.service.PayService;
import com.platform.modules.bk.service.BkCustomerService;
import com.platform.modules.mall.activity.service.GoShoppingService;
import com.platform.modules.mall.entity.*;
import com.platform.modules.mall.goods.utils.CreateOrderUtil;
import com.platform.modules.mall.service.*;
import com.platform.modules.sys.service.SysConfigService;
import io.swagger.annotations.*;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 作者: @author  <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@Api(tags = "ApiOrderController|订单管理控制器")
@RestController
@RequestMapping("/app/order")
public class AppOrderController extends AppBaseController {
    @Autowired
    private MallOrderService orderService;
    @Autowired
    private MallOrderGoodsService orderGoodsService;
    @Autowired
    private MallGoodsSkuService goodsSkuService;
    @Autowired
    private MallGoodsService goodsService;
    @Autowired
    private MallCartService cartService;
    @Autowired
    private KdniaoService apiKdniaoService;
    @Autowired
    private WxSendMsgService sendMsgService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private MallCommentService commentService;
    @Autowired
    private MallShopsGoodsService shopsGoodsService;
    @Autowired
    private MallShopsService shopsService;
    @Autowired
    private PayService payService;

    @Autowired
    private MallUserCouponService userCouponService;
    @Autowired
    private JedisUtil jedisUtil;
    @Autowired
    private BkCustomerService bkCustomerService;
    @Autowired
    private MallUserIntegralLogService mallUserIntegralLogService;
    @Autowired
    private MallUserService userService;
    @Autowired
    private MallUserCardService userCardService;
    @Autowired
    private MallCardSnService mallCardSnService;
    @Autowired
    private GoShoppingService goShoppingService;

    /**
     * 获取订单列表
     */
    @GetMapping("list")
    @ApiOperation(value = "订单列表", notes = "获取订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "orderStatus", value = "订单状态", required = true, dataType = "int", example = "1"),
            @ApiImplicitParam(paramType = "query", name = "current", value = "当前页码", example = "1", dataType = "int"),
            @ApiImplicitParam(paramType = "query", name = "limit", value = "每页条数", example = "10", dataType = "int")
    })
    public RestResponse list(@LoginUser MallUserEntity loginUser, Integer orderStatus, Integer orderType,
                             @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer limit) {
        Map<String, Object> params = new HashMap<>();
        params.put("page", current);
        params.put("limit", limit);
        params.put("userId", loginUser.getId());
        if (orderStatus != -2) {
            params.put("orderStatus", orderStatus);
        }
        if (Constant.OrderStatus.QRSH.getValue().equals(orderStatus)) {
            params.put("notExists", orderStatus);
        }
        if (orderType == null) {
            return RestResponse.error(201, "请选择订单类型");
        }

        params.put("orderType", orderType);
        /*过滤无效订单，谢谢惠顾*/
        params.put("noOrderType", CreateOrderUtil.OrderType.WU_XIAO_ORDER.getValue());

        Page<MallOrderEntity> data = orderService.queryPage(params);
        //
        for (MallOrderEntity item : data.getRecords()) {
            //订单的商品
            List<MallOrderGoodsEntity> goodsList = orderGoodsService.list(new QueryWrapper<MallOrderGoodsEntity>().eq("ORDER_ID", item.getId()));
            Integer goodsCount = 0;
            for (MallOrderGoodsEntity orderGoodsEntity : goodsList) {
                goodsCount += orderGoodsEntity.getNumber();
            }
//            item.setCommentCount(commentService.count(new QueryWrapper<MallCommentEntity>().eq("ORDER_ID", item.getId())));
            item.setGoodsCount(goodsCount);
            item.setOrderGoodsEntityList(goodsList);
        }
        return RestResponse.success().put("data", data);
    }

    /**
     * 获取订单详情
     */
    @GetMapping("detail")
    @ApiOperation(value = "订单详情", notes = "根据订单ID获取订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "orderId", value = "订单ID", required = true, dataType = "int", example = "1")
    })
    public RestResponse detail(@LoginUser MallUserEntity loginUser, String orderId) {
        Map<String, Object> resultObj = new HashMap<>(4);
        //
        MallOrderEntity orderInfo = orderService.queryById(orderId);
        if (null == orderInfo) {
            return RestResponse.error("订单不存在！");
        }
        if (!loginUser.getId().equals(orderInfo.getUserId())) {
            return RestResponse.error("越权操作！");
        }
        //订单的商品
        List<MallOrderGoodsEntity> orderGoods = orderGoodsService.list(new QueryWrapper<MallOrderGoodsEntity>().eq("ORDER_ID", orderId));

        orderInfo.setCommentCount(commentService.count(new QueryWrapper<MallCommentEntity>().eq("ORDER_ID", orderId)));
        MallGoodsEntity goodsEntity = goodsService.getById(orderGoods.get(0).getGoodsId());
        // 电子卡券显示卡密
        if (goodsEntity != null) {
            if(goodsEntity.getGoodsType().equals(Constant.GoodsType.CARD_COUPON.getValue())){
                resultObj.put("cardSn", userCardService.list(new LambdaQueryWrapper<MallUserCardEntity>()
                        .eq(MallUserCardEntity::getUserId, orderInfo.getUserId()).eq(MallUserCardEntity::getOrderId, orderId)));
            }
            resultObj.put("goodsDesc",goodsEntity.getGoodsDesc());
        }
        resultObj.put("orderInfo", orderInfo);
        resultObj.put("orderGoods", orderGoods);
        return RestResponse.success(resultObj);
    }

    /**
     * 提交订单
     */
    @PostMapping("submitOrder")
    @ApiOperation(value = "提交订单", notes = "购物车页面提交订单，商品为购物车中已经选中的")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "fromType", value = "用户下单来源类型 1:微信小程序 2:微信公众号 3:app 4:H5 5:支付宝小程序 6:QQ小程序"),
                    @ExampleProperty(mediaType = "postscript", value = "订单说明"),
                    @ExampleProperty(mediaType = "checkedAddress", value = "AddressVo"),
                    @ExampleProperty(mediaType = "type", value = "buy,直接购买传buy，购物车进来不用传值"),
                    @ExampleProperty(mediaType = "orderType", value = "订单类型，1普通订单，2支行订单，3秒杀订单，4卡券订单，5积分订单"),
                    @ExampleProperty(mediaType = "integralMoney", value = "抵扣积分"),
                    @ExampleProperty(mediaType = "couponId", value = "couponId"),
                    @ExampleProperty(mediaType = "shopsId", value = "1")
            }), required = true, dataType = "string")
    })
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public RestResponse submitOrder(@LoginUser MallUserEntity loginUser, @RequestBody JSONObject jsonParam) {
        String postscript = jsonParam.getString("postscript");
        String shopsId = jsonParam.getString("shopsId");
        String type = jsonParam.getString("type");
        String couponId = jsonParam.getString("couponId");
        Integer fromType = jsonParam.getInteger("fromType");
        BigDecimal integralMoney = jsonParam.getBigDecimal("integralMoney");

        MallAddressEntity addressVo = jsonParam.getObject("checkedAddress", MallAddressEntity.class);
        // 抵扣积分不为零，用户可用积分小于抵扣积分
        if (integralMoney != null && (integralMoney.subtract(loginUser.getSignAllIntegral()).compareTo(BigDecimal.ZERO) == -1)) {
            return RestResponse.error("可用积分不足");
        }

        // * 获取要购买的商品和总价
        List<MallCartEntity> checkedGoodsList = new ArrayList<>();
        BigDecimal goodsTotalPrice;
        MallOrderEntity orderInfo = new MallOrderEntity();

        // 是直接购买的
        if ("buy".equals(type)) {
            BuyGoodsVo goodsVO = (BuyGoodsVo) jedisUtil.getObject(Constant.MTM_CACHE + "goods" + loginUser.getId());

            MallGoodsEntity entity = goodsService.getById(goodsVO.getGoodsId());

            MallOrderGoodsEntity orderGoodsEntity = new MallOrderGoodsEntity();
            orderGoodsEntity.setUserId(loginUser.getId());
            orderGoodsEntity.setAddTime(DateUtils.format(new Date()));
            orderGoodsEntity.setGoodsId(goodsVO.getGoodsId());

            MallCartEntity cartVo = new MallCartEntity();
            // 实物需要判断邮寄地址
            if (entity.getGoodsType() == 0) {
                if (addressVo == null || StringUtils.isBlank(addressVo.getId())) {
                    return RestResponse.error("请选择邮寄地址");
                }
                orderInfo.setOrderType(Constant.NORMAL_ORDER);
                MallGoodsSkuEntity productInfo = goodsSkuService.getById(goodsVO.getSkuId());
                if (null == productInfo || productInfo.getGoodsNumber() < goodsVO.getNumber()) {
                    throw new BusinessException("商品库存不足");
                }
                productInfo.setGoodsNumber(productInfo.getGoodsNumber() - goodsVO.getNumber());
                goodsSkuService.update(productInfo);
                //计算订单的费用
                //商品总价
                goodsTotalPrice = productInfo.getRetailPrice().multiply(new BigDecimal(goodsVO.getNumber()));
                cartVo.setRetailPrice(productInfo.getRetailPrice());
            } else {
                orderInfo.setOrderType(Constant.CARD_ORDER);
                goodsTotalPrice = entity.getRetailPrice().multiply(new BigDecimal(goodsVO.getNumber()));
                cartVo.setRetailPrice(entity.getRetailPrice());
            }
            orderInfo.setActivityType(entity.getGoodsTag());
            orderGoodsEntity = orderGoodsService.queryUserBuyNumber(orderGoodsEntity);
            if (entity.getIsLimited() > 0 && NumberUtils.toInt(orderGoodsEntity.getId(), 0) + goodsVO.getNumber() > entity.getIsLimited()) {
                throw new BusinessException("每人每天限购数量" + entity.getIsLimited());
            }

            if (null == entity.getGoodsNumber() || entity.getGoodsNumber() < goodsVO.getNumber()) {
                throw new BusinessException("商品库存不足");
            }
            entity.setGoodsNumber(entity.getGoodsNumber() - goodsVO.getNumber());

            MallShopsGoodsEntity shopsGoodsEntity = shopsGoodsService.getOne(new LambdaQueryWrapper<MallShopsGoodsEntity>().eq(MallShopsGoodsEntity::getGoodsId, entity.getId()), false);
            shopsId = shopsGoodsEntity.getShopsId();


            goodsService.updateById(entity);

            cartVo.setGoodsName(entity.getName());
            cartVo.setNumber(goodsVO.getNumber());
            cartVo.setGoodsId(goodsVO.getGoodsId());
            cartVo.setSkuId(goodsVO.getSkuId());
            cartVo.setListPicUrl(entity.getListPicUrl());
            cartVo.setGoodsSn(entity.getGoodsSn());
            cartVo.setGoodsSpecifitionNameValue(goodsVO.getSelectedText());
            checkedGoodsList.add(cartVo);
        } else {
            //获取要购买的商品
            Map<String, Object> param = new HashMap<>(4);
            param.put("userId", loginUser.getId());
            param.put("checked", 1);
            if (StringUtils.isNotBlank(shopsId)) {
                param.put("shopsId", shopsId);
            } else {
                param.put("normal", "0");
            }
            checkedGoodsList = cartService.queryAll(param);
            if (null == checkedGoodsList || checkedGoodsList.size() == 0) {
                return RestResponse.error("请选择商品！");
            }

            goodsTotalPrice = new BigDecimal(0.00);
            for (MallCartEntity cartItem : checkedGoodsList) {
                //减商品库存
                MallGoodsEntity goodsVo = goodsService.getById(cartItem.getGoodsId());
                if (null == goodsVo.getGoodsNumber() || goodsVo.getGoodsNumber() < cartItem.getNumber()) {
                    throw new BusinessException(cartItem.getGoodsName() + "库存不足");
                }
                goodsVo.setGoodsNumber(goodsVo.getGoodsNumber() - cartItem.getNumber());
                goodsService.updateById(goodsVo);
                //非店铺订单减产品库存
                if (StringUtils.isNullOrEmpty(shopsId)) {
                    //减产品库存
                    MallGoodsSkuEntity goodsSkuEntity = goodsSkuService.getById(cartItem.getSkuId());
                    if (null == goodsSkuEntity || goodsSkuEntity.getGoodsNumber() < cartItem.getNumber()) {
                        throw new BusinessException(cartItem.getGoodsName() + "库存不足");
                    }
                    goodsSkuEntity.setGoodsNumber(goodsSkuEntity.getGoodsNumber() - cartItem.getNumber());
                    goodsSkuService.update(goodsSkuEntity);
                } else {
                    //店铺订单减库存
                    MallShopsGoodsEntity shopsGoodsEntity = shopsGoodsService.getOne(new LambdaQueryWrapper<MallShopsGoodsEntity>()
                                    .eq(MallShopsGoodsEntity::getGoodsId, goodsVo.getId())
                                    .eq(MallShopsGoodsEntity::getShopsId, shopsId)
                            , false);
                    if (null == shopsGoodsEntity.getGoodsNumber() || shopsGoodsEntity.getGoodsNumber() < cartItem.getNumber()) {
                        throw new BusinessException(cartItem.getGoodsName() + "库存不足");
                    }
                    shopsGoodsEntity.setGoodsNumber(shopsGoodsEntity.getGoodsNumber() - cartItem.getNumber());

                    shopsGoodsService.update(shopsGoodsEntity);
                }

                //统计商品总价
                goodsTotalPrice = goodsTotalPrice.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber())));
            }
        }

        BigDecimal shippingFee = BigDecimal.valueOf(0);
        //非店铺订单加上运费
        if (StringUtils.isNullOrEmpty(shopsId)) {
            //免邮门槛
            String shippingFeeFre = sysConfigService.getValue(Constant.SHIPPING_FEE_FREE, "80");
            if (goodsTotalPrice.compareTo(new BigDecimal(shippingFeeFre)) <= 0) {
                shippingFee = new BigDecimal(sysConfigService.getValue(Constant.SHIPPING_FEE, "12"));
            }
        }
        String orderSn = StringUtils.generateOrderNumber();

        //优惠金额
        BigDecimal subPrice = new BigDecimal(0);
//        if (StringUtils.isNotBlank(couponId)) {
//            MallCouponEntity couponEntity = couponService.getById(couponId);
//            if (null != couponEntity && couponEntity.getStatus() == 1) {
//                MallUserCouponEntity userCouponEntity = userCouponService.getOne(new QueryWrapper<MallUserCouponEntity>().eq("COUPON_ID", couponId).eq("USER_ID", loginUser.getId()));
//                if (userCouponEntity.getStatus() == 0) {
//                    userCouponEntity.setStatus(1);
//                    userCouponEntity.setUsedTime(new Date());
//                    userCouponEntity.setOrderId(orderSn);
//                    userCouponService.update(userCouponEntity);
//                    // 商品总价 >= 最低消费金额
//                    BigDecimal minPrice = couponEntity.getMinPrice();
//                    if (goodsTotalPrice.compareTo(minPrice) > -1) {
//                        Integer couponType = couponEntity.getCouponType();
//                        //代金券类型
//                        if (Constant.CouponType.DJQ.getValue().equals(couponType)) {
//                            subPrice = couponEntity.getSubPrice();
//                        }
//                        //折扣
//                        if (Constant.CouponType.ZK.getValue().equals(couponType)) {
//                            //这里使用商品总价乘以（1-折扣/10），然后四舍五入保留两位小数
//                            subPrice = new BigDecimal(1).subtract(couponEntity.getDiscount().divide(new BigDecimal(10))).multiply(goodsTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
//                        }
//                    }
//                }
//            }
//        }

        //订单价格计算//订单的总价
        BigDecimal orderTotalPrice = goodsTotalPrice.add(shippingFee);
        BigDecimal actualPrice = orderTotalPrice.subtract(subPrice);

        orderInfo.setId(orderSn);
        orderInfo.setOrderSn(orderSn);
        orderInfo.setUserId(loginUser.getId());
        orderInfo.setCouponId(couponId);
        orderInfo.setCouponPrice(subPrice);
        if (addressVo != null) {
            orderInfo.setConsignee(addressVo.getUserName());
            orderInfo.setMobile(addressVo.getMobile());
            orderInfo.setCountry(addressVo.getNationalCode());
            orderInfo.setProvince(addressVo.getProvinceName());
            orderInfo.setCity(addressVo.getCityName());
            orderInfo.setDistrict(addressVo.getCountyName());
            orderInfo.setAddress(addressVo.getDetailInfo());
            orderInfo.setPostalCode(addressVo.getPostalCode());
        }
        orderInfo.setFromType(fromType);
        //留言
        orderInfo.setPostscript(postscript);
        orderInfo.setAddTime(new Date());
        orderInfo.setExpireTime(DateUtils.addDateMinutes(new Date(), Integer.parseInt(sysConfigService.getValue(Constant.ORDER_EXPIRE, "30"))));
        orderInfo.setActualPrice(actualPrice);
        orderInfo.setOrderPrice(orderTotalPrice);
        // 待付款
        orderInfo.setOrderStatus(Constant.OrderStatus.DFK.getValue());
        orderInfo.setShippingStatus(Constant.ShippingStatus.WFH.getValue());
        orderInfo.setPayStatus(Constant.PayStatus.WFK.getValue());
        orderInfo.setShippingFee(shippingFee);
        orderInfo.setIntegralMoney(new BigDecimal(0));
        //插入订单信息和订单商品
        orderService.save(orderInfo);
        if (null == orderInfo.getId()) {
            return RestResponse.error("订单提交失败！");
        }
        List<MallOrderGoodsEntity> orderGoodsData = new ArrayList<>();
        for (MallCartEntity goodsItem : checkedGoodsList) {
            MallOrderGoodsEntity orderGoodsVo = new MallOrderGoodsEntity();
            orderGoodsVo.setOrderId(orderInfo.getId());
            orderGoodsVo.setGoodsId(goodsItem.getGoodsId());
            orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn());
            orderGoodsVo.setSkuId(goodsItem.getSkuId());
            orderGoodsVo.setGoodsName(goodsItem.getGoodsName());
            orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl());
            orderGoodsVo.setMarketPrice(goodsItem.getMarketPrice());
            orderGoodsVo.setRetailPrice(goodsItem.getRetailPrice());
            orderGoodsVo.setNumber(goodsItem.getNumber());
            orderGoodsVo.setGoodsSpecifitionNameValue(goodsItem.getGoodsSpecifitionNameValue());
            orderGoodsData.add(orderGoodsVo);
        }
        orderGoodsService.saveBatch(orderGoodsData);

        // 是直接购买的
        if (!"buy".equals(type)) {
            //清空购物车已选中的商品
            cartService.remove(new QueryWrapper<MallCartEntity>().eq("USER_ID", loginUser.getId()).eq("checked", 1));
        }

        orderInfo.setOrderGoodsEntityList(orderGoodsData);

        try {
            if (fromType.equals(Constant.FromType.MA.getValue())) {
                // 微信通知
                sendMsgService.notifyPaySuccess(orderInfo, Constant.STR_ZERO);
            } else if (orderInfo.getFromType().equals(Constant.FromType.MP.getValue())) {
                //TODO 公众号下单，发送消息
            } else if (orderInfo.getFromType().equals(Constant.FromType.MA.getValue())) {
                //TODO 小程序下单，发送消息
            } else if (orderInfo.getFromType().equals(Constant.FromType.QQ.getValue())) {
                //TODO QQ小程序下单，发送消息
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RestResponse.success().put("data", orderInfo);
    }


    /**
     * 提交积分兑换订单
     */
    @PostMapping("submitIntegralOrder")
    @ApiOperation(value = "提交积分兑换订单", notes = "提交积分兑换订单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "fromType", value = "用户下单来源类型 1:微信小程序 2:微信公众号 3:app 4:H5 5:支付宝小程序 6:QQ小程序"),
                    @ExampleProperty(mediaType = "postscript", value = "订单说明"),
                    @ExampleProperty(mediaType = "checkedAddress", value = "AddressVo"),
                    @ExampleProperty(mediaType = "deliveryType", value = "配送类型，0送货上门，1上门自取"),
                    @ExampleProperty(mediaType = "couponId", value = "couponId"),
                    @ExampleProperty(mediaType = "shopsId", value = "1")
            }), required = true, dataType = "string")
    })
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public RestResponse submitIntegralOrder(@LoginUser MallUserEntity loginUser, @RequestBody JSONObject jsonParam) {

        String goodsId = jsonParam.getString("goodsId");
        Integer number = jsonParam.getInteger("number");
        String postscript = jsonParam.getString("postscript");
        String shopsId = jsonParam.getString("shopsId");
//        String type = jsonParam.getString("type");
        String couponId = jsonParam.getString("couponId");
        Integer fromType = jsonParam.getInteger("fromType");
        Integer deliveryType = jsonParam.getInteger("deliveryType");
        MallAddressEntity addressVo = null;

        if(StringUtils.isBlank(goodsId) || fromType == null || deliveryType == null || number == null){
            throw new BusinessException("参数错误！");
        }

        if (1 != deliveryType) {
            addressVo = jsonParam.getObject("checkedAddress", MallAddressEntity.class);
            if (addressVo == null || StringUtils.isBlank(addressVo.getId())) {
                return RestResponse.error("请填写收货地址");
            }
        }
//        if (StringUtils.isBlank(loginUser.getCustomerNo())) {
//            return RestResponse.error(204, "请前往我的-常用功能-绑定积分信息页面中绑定积分信息");
//        }
//        BkCustomerEntity customerEntity = bkCustomerService.getById(loginUser.getCustomerNo());
//        if (customerEntity == null) {
//            return RestResponse.error(204, "请前往我的-常用功能-绑定积分信息页面中绑定积分信息");
//        }
        BigDecimal allIntegral = loginUser.getSignAllIntegral();
//        .add(customerEntity.getAvailablePoints());
        //  获取要购买的商品和总价
        List<MallCartEntity> checkedGoodsList = new ArrayList<>();
        BigDecimal goodsTotalPrice;
        BigDecimal goodsIntegralTotalPrice;
        MallOrderEntity orderInfo = new MallOrderEntity();
        orderInfo.setDeliveryType(deliveryType);
        orderInfo.setOrderType(Constant.INTEGRAL_ORDER);

//        BuyGoodsVo goodsVO = (BuyGoodsVo) jedisUtil.getObject(Constant.MTM_CACHE + "goods" + loginUser.getId());

        MallGoodsEntity entity = goodsService.getById(goodsId);
        // 指定商品的积分优惠
//        String discountsIntegralGoods = sysConfigService.getValue(Constant.DISCOUNTS_INTEGRAL_GOODS);
//        if (discountsIntegralGoods != null && discountsIntegralGoods.indexOf(goodsVO.getGoodsId()) >= 0) {
//            BigDecimal discountsIntegral = BigDecimal.valueOf(Short.parseShort(sysConfigService.getValue(Constant.DISCOUNTS_INTEGRAL, "0")));
//            entity.setCustomerIntegral(entity.getCustomerIntegral().subtract(discountsIntegral));
//        }
        if(entity.getIsLimited() > 0){
            MallOrderGoodsEntity orderGoodsEntity = new MallOrderGoodsEntity();
            orderGoodsEntity.setUserId(loginUser.getId());
            orderGoodsEntity.setAddTime(DateUtils.format(new Date()));
            orderGoodsEntity.setGoodsId(goodsId);
            orderGoodsEntity = orderGoodsService.queryUserBuyNumber(orderGoodsEntity);
            if (NumberUtils.toInt(orderGoodsEntity.getId(), 0) + number > entity.getIsLimited()) {
                throw new BusinessException("每人每天限购数量" + entity.getIsLimited());
            }
        }

        if (null == entity.getGoodsNumber() || entity.getGoodsNumber() < number) {
            throw new BusinessException("商品库存不足");
        }
        entity.setGoodsNumber(entity.getGoodsNumber() - number);

        MallCartEntity cartVo = new MallCartEntity();
        // 根据商品id查找店铺id
//        MallShopsGoodsEntity shopsGoodsEntity = shopsGoodsService.getOne(new LambdaQueryWrapper<MallShopsGoodsEntity>()
//                .eq(!"1".equals(shopsId), MallShopsGoodsEntity::getShopsId, shopsId)
//                .eq(MallShopsGoodsEntity::getGoodsId, entity.getId()), false);
//        if ("1".equals(shopsId)) {
//            shopsId = shopsGoodsEntity.getShopsId();
//        }

        goodsIntegralTotalPrice = entity.getCustomerIntegral().multiply(new BigDecimal(number));
        goodsTotalPrice = entity.getCustomerIntegral().multiply(new BigDecimal(number));
        cartVo.setRetailPrice(entity.getCustomerIntegral());
        cartVo.setMarketPrice(entity.getMarketPrice());
        // 没有规格则使用商品的金额和数量
        // 修改库存
        // 减商品库存
        if(!goodsService.lambdaUpdate().setSql("GOODS_NUMBER = GOODS_NUMBER - " + number)
                .eq(MallGoodsEntity::getId,goodsId)
                .ge(MallGoodsEntity::getGoodsNumber,number)
                .update()){
            throw new BusinessException("商品库存不足..");
        }
//        goodsService.updateById(entity);
//        shopsGoodsEntity.setGoodsNumber(shopsGoodsEntity.getGoodsNumber() - goodsVO.getNumber());
//        shopsGoodsService.updateById(shopsGoodsEntity);

        cartVo.setGoodsName(entity.getName());
        cartVo.setNumber(number);
        cartVo.setGoodsId(goodsId);
//        cartVo.setSkuId(goodsVO.getSkuId());
        cartVo.setListPicUrl(entity.getListPicUrl());
        cartVo.setGoodsSn(entity.getGoodsSn());
//        cartVo.setGoodsSpecifitionNameValue(goodsVO.getSelectedText());
        checkedGoodsList.add(cartVo);

        BigDecimal shippingFee = BigDecimal.ZERO;
        String orderSn = StringUtils.generateOrderNumber();

        //优惠金额
        BigDecimal subPrice = BigDecimal.ZERO;

        //订单价格计算//订单的总价
        BigDecimal actualPrice = goodsIntegralTotalPrice;
        if (allIntegral.subtract(actualPrice).compareTo(BigDecimal.ZERO) < 0) {
            throw new BusinessException("您的积分不足");
        }

        if(!userService.lambdaUpdate()
                .setSql(String.format("SIGN_USED_INTEGRAL = SIGN_USED_INTEGRAL +  %s,SIGN_ALL_INTEGRAL = SIGN_ALL_INTEGRAL - %s",actualPrice,actualPrice))
                .eq(MallUserEntity::getId,loginUser.getId())
                .ge(MallUserEntity::getSignAllIntegral,actualPrice)
                .update()){
            throw new BusinessException("您的积分不足...");
        }

        // 记录用户积分扣除
        mallUserIntegralLogService.add(loginUser.getId(), actualPrice, allIntegral, Constant.IntegralType.PAYOUT, "积分兑换商品");
        // 判断用户活动中获得的积分是否够抵扣
//        boolean greater = actualPrice.compareTo(loginUser.getSignAllIntegral()) > 0,
//                equal = actualPrice.compareTo(loginUser.getSignAllIntegral()) == 0,
//                less = actualPrice.compareTo(loginUser.getSignAllIntegral()) < 0,
//                flag = userService.update(new LambdaUpdateWrapper<MallUserEntity>()
//                        .set(MallUserEntity::getSignUsedIntegral, loginUser.getSignUsedIntegral().add(actualPrice))
//                        .set(greater || equal, MallUserEntity::getSignAllIntegral, 0)
//                        .set(less, MallUserEntity::getSignAllIntegral, loginUser.getSignAllIntegral().subtract(actualPrice))
//                        .eq(MallUserEntity::getId, loginUser.getId())
//                );
        // 商品积分大于用户活动获取的积分则抵扣后在减去存款积分，其他直接抵扣用户活动获取的积分
//        if (greater) {
//            bkCustomerService.updatePoints(actualPrice.subtract(loginUser.getSignAllIntegral()),
//                    Constant.IntegralType.PAYOUT.getValue(), customerEntity.getCustomerNo());
//        }

//        if (!flag) {
//            throw new BusinessException("系统繁忙请稍后重试");
//        }

        orderInfo.setId(orderSn);
        orderInfo.setOrderSn(orderSn);
        orderInfo.setUserId(loginUser.getId());
        orderInfo.setCouponId(couponId);
        orderInfo.setCouponPrice(subPrice);
        if (addressVo != null) {
            orderInfo.setConsignee(addressVo.getUserName());
            orderInfo.setMobile(addressVo.getMobile());
            orderInfo.setCountry(addressVo.getNationalCode());
            orderInfo.setProvince(addressVo.getProvinceName());
            orderInfo.setCity(addressVo.getCityName());
            orderInfo.setDistrict(addressVo.getCountyName());
            orderInfo.setAddress(addressVo.getDetailInfo());
            orderInfo.setPostalCode(addressVo.getPostalCode());
        }
        orderInfo.setShopsId(shopsId);
        orderInfo.setFromType(fromType);
        //留言
        orderInfo.setPostscript(postscript);
        orderInfo.setAddTime(new Date());
        orderInfo.setPayTime(orderInfo.getAddTime());
        orderInfo.setExpireTime(DateUtils.addDateMinutes(new Date(), Integer.parseInt(sysConfigService.getValue(Constant.ORDER_EXPIRE, "30"))));
        orderInfo.setActualPrice(BigDecimal.ZERO);
        orderInfo.setOrderPrice(goodsTotalPrice);
        // 已付款
        orderInfo.setOrderStatus(Constant.OrderStatus.YFK.getValue());
        orderInfo.setShippingStatus(Constant.ShippingStatus.WFH.getValue());
        orderInfo.setPayStatus(Constant.PayStatus.YFK.getValue());
        orderInfo.setShippingFee(shippingFee);
        orderInfo.setPayType(Constant.PayType.JF.getValue());
        //  需要抵扣积分数量
        orderInfo.setIntegralMoney(goodsIntegralTotalPrice);
        //插入订单信息和订单商品
        orderService.save(orderInfo);

        if (null == orderInfo.getId()) {
            throw new BusinessException("订单提交失败！");
        }
        List<MallOrderGoodsEntity> orderGoodsData = new ArrayList<>();
        for (MallCartEntity goodsItem : checkedGoodsList) {
            MallOrderGoodsEntity orderGoodsVo = new MallOrderGoodsEntity();
            orderGoodsVo.setOrderId(orderInfo.getId());
            orderGoodsVo.setGoodsId(goodsItem.getGoodsId());
            orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn());
            orderGoodsVo.setSkuId(goodsItem.getSkuId());
            orderGoodsVo.setGoodsName(goodsItem.getGoodsName());
            orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl());
            orderGoodsVo.setMarketPrice(goodsItem.getMarketPrice());
            orderGoodsVo.setRetailPrice(goodsItem.getRetailPrice());
            orderGoodsVo.setNumber(goodsItem.getNumber());
            orderGoodsVo.setGoodsSpecifitionNameValue(goodsItem.getGoodsSpecifitionNameValue());
            orderGoodsData.add(orderGoodsVo);
        }
        orderGoodsService.saveBatch(orderGoodsData);
        // 电子卡券需要发送卡券
//        if (entity.getGoodsType().equals(Constant.GoodsType.CARD_COUPON.getValue())) {
//            mallCardSnService.sendCard(orderInfo);
//        }

        // 电子卡券需要发送卡券
        if (entity.getGoodsType().equals(Constant.GoodsType.CARD_COUPON.getValue())) {
            mallCardSnService.sendCard(orderInfo);
            orderInfo.setOrderStatus(Constant.OrderStatus.QRSH.getValue());
            orderInfo.setShippingStatus(Constant.ShippingStatus.YSH.getValue());
            orderInfo.setPayStatus(Constant.PayStatus.YFK.getValue());
            orderService.update(orderInfo);
        }

        orderInfo.setOrderGoodsEntityList(orderGoodsData);


        //  非1是送货上门需要发送通知提醒商户发货
//        if (1 != deliveryType) {
//            MallShopsEntity shopsEntity = shopsService.getById(shopsId);
//            // 店铺添加openid则发送通知
//            if (shopsEntity != null && StringUtils.isNotBlank(shopsEntity.getOpenid())) {
//                sendMsgService.sendUniformMsg(orderInfo, 6, shopsEntity.getOpenid());
//            }
//        }z

        try {
            if (fromType.equals(Constant.FromType.MA.getValue())) {
                // 微信通知
                // sendMsgService.notifyPaySuccess(orderInfo, 0);
            } else if (orderInfo.getFromType().equals(Constant.FromType.MP.getValue())) {
                // 公众号下单，发送消息
            } else if (orderInfo.getFromType().equals(Constant.FromType.MA.getValue())) {
                // 小程序下单，发送消息
            } else if (orderInfo.getFromType().equals(Constant.FromType.QQ.getValue())) {
                // QQ小程序下单，发送消息
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RestResponse.success().put("data", orderInfo);
    }

    @PostMapping("confirmOrder")
    @ApiOperation(value = "确认收货", notes = "确认收货")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "orderId", name = "orderId", value = "JSON格式参数", required = true, dataType = "string")
    })
    public RestResponse confirmOrder(@LoginUser MallUserEntity loginUser, @RequestBody JSONObject params) {
        String orderId = params.getString("orderId");
        MallOrderEntity orderInfo = orderService.getById(orderId);

        if (!loginUser.getId().equals(orderInfo.getUserId())) {
            return RestResponse.error("越权操作！");
        }

        orderService.confirmReceive(orderId);

        return RestResponse.success("确认成功");
    }

    /**
     * 联联订单退货
     */
    @GetMapping("returnOrder")
    @ApiOperation(value = "联联订单退货", notes = "联联订单退货")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "params", name = "id", value = "订单ID", required = true, dataType = "string")
    })
    @Transactional(rollbackFor = Exception.class)
    public RestResponse returnOrder(String id) {
        orderService.statusChange(id,403,getUserId());
        return RestResponse.success();
    }

    /**
     * 取消订单
     */
    @PostMapping("cancelOrder")
    @ApiOperation(value = "取消订单", notes = "取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "orderId", value = "1")
            }), required = true, dataType = "string")
    })
    @Transactional(rollbackFor = Exception.class)
    public RestResponse cancelOrder(@LoginUser MallUserEntity loginUser, @RequestBody JSONObject jsonParam) {
        String orderId = jsonParam.getString("orderId");

        MallOrderEntity orderVo = orderService.getById(orderId);
        if (orderVo==null){
            return RestResponse.error("未找到该订单，请使用正确的订单号");
        }
        if (!loginUser.getId().equals(orderVo.getUserId())) {
            return RestResponse.error("越权操作！");
        }
        if (orderVo.getOrderStatus().equals(Constant.OrderStatus.YFH.getValue())) {
            return RestResponse.error("已发货，不能取消！");
        } else if (orderVo.getOrderStatus().equals(Constant.OrderStatus.QRSH.getValue())) {
            return RestResponse.error("已收货，不能取消！");
        }
        /*活动相关订单取消处理*/
        if (StringUtils.isNotBlank(orderVo.getActivityId())){
            goShoppingService.cancelOrder(orderVo);
            return RestResponse.success();
        }

        return payService.refund(orderVo);
    }

    /**
     * 修改秒杀订单的收货地址
     */
    @PostMapping("updateOrderAddress")
    @ApiOperation(value = "取消订单", notes = "取消订单")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "orderId", value = "1")
            }), required = true, dataType = "string")
    })
    @Transactional(rollbackFor = Exception.class)
    public RestResponse updateOrderAddress(@LoginUser MallUserEntity loginUser, @RequestBody JSONObject jsonParam) {
        String orderId = jsonParam.getString("orderId");

        MallOrderEntity orderVo = orderService.getById(orderId);
        if (!loginUser.getId().equals(orderVo.getUserId())) {
            return RestResponse.error("越权操作！");
        }
        String consignee = jsonParam.getString("consignee"),
                province = jsonParam.getString("province"),
                city = jsonParam.getString("city"),
                district = jsonParam.getString("district"),
                address = jsonParam.getString("address"),
                mobile = jsonParam.getString("mobile");
        orderVo.setConsignee(consignee);
        orderVo.setProvince(province);
        orderVo.setCity(city);
        orderVo.setDistrict(district);
        orderVo.setAddress(address);
        orderVo.setMobile(mobile);
        orderService.update(orderVo);

        return RestResponse.success();
    }


    /**
     * 跟踪快递轨迹
     *
     * @param shippingCode 快递公司code 如顺丰：SF
     * @param shippingNo   快递单号
     * @return
     */
    @GetMapping("getLogistics")
    @ApiOperation(value = "快递查询", notes = "跟踪快递轨迹")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "shippingCode", value = "快递公司code 如顺丰：SF", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "shippingNo", value = "快递单号", required = true, dataType = "string")
    })
    public RestResponse getLogistics(String shippingCode, String shippingNo) {
        try {
            List<Map<String, Object>> traces = apiKdniaoService.getOrderTraces(shippingCode, shippingNo);
            if (traces.size() > 0) {
                //根据时间排序物流轨迹
                traces.sort((Comparator<Map>) (o1, o2) -> {
                    if (DateUtils.strToTime(o1.get("AcceptTime") + "") > DateUtils.strToTime(o2.get("AcceptTime") + "")) {
                        return -1;
                    }
                    return 1;
                });
                return RestResponse.success().put("traces", traces);
            } else {
                return RestResponse.error("暂无轨迹信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.error("查询失败！");
    }
}
